package AndroidAction;

/**
 * Created by zhe.xiao on 2017/7/12.
 */

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.BySelector;
import android.support.test.uiautomator.Direction;
import android.support.test.uiautomator.Tracer;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.Until;
import android.util.Log;

import static HomeElements.ZuiJinGuanZhuData.*;

import org.junit.Assert;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import util.GetDevice;
import util.UIHelper;

public class ElementsAction {
    private static Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    //    private static final UiDevice device = UiDevice.getInstance(instrumentation);
    public UiDevice device = GetDevice.getDevice();
    public BySelector by;
    private static final ElementsAction ea = new ElementsAction();

    private ElementsAction() {

    }

    public static ElementsAction getInstrent() {
        return ea;
    }

    /**
     * 启动指定的app
     *
     * @param p
     */
    public void startApp(String p) {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        final Intent intent = context.getPackageManager().getLaunchIntentForPackage(p);
//        final Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        ComponentName ca = new ComponentName(p,a);
//        intent.setComponent(ca);
        context.startActivity(intent);
    }

    /**
     * 通过不同的方法查找元素
     *
     * @param id
     * @param value
     * @param ob
     * @return
     */
    public Object getElements(String id, String value, Object... ob) {
        Object b = null;
        //id
        if (id == "id") {
            if (ob.length > 0) {
                b = this.findId(value, ob[0]);
            } else {
                b = this.findId(value);
            }
        }
        //text
        if (id == "text") {

        }
        //res
        if (id == "res") {

        }
        //class
        if (id == "class") {

        }
        return b;
    }

    /**
     * 通过id查找元素
     *
     * @param s
     * @param b
     * @return
     */
    public Object findId(String s, Object... b) {
        this.sleep(5000);
        device.wait(Until.findObject(By.res(s)), 20000);
        Object u2 = null;
        if (b.length > 0) {
            if (b[0] instanceof UiObject2) {
                u2 = ((UiObject2) b[0]).findObject(By.res(s));
            }
        } else {
            u2 = device.findObject(By.res(s));
        }
        return u2;
    }


    /**
     * 向右滑动元素
     *
     * @param b
     */
    public void swipForScrollableRight(Object b) {
        if (b instanceof UiObject2) {
            ((UiObject2) b).scroll(Direction.RIGHT, 0.8f);
        }
        if (b instanceof UiObject) {
            try {
                new UiScrollable(((UiObject) b).getSelector()).setAsHorizontalList().scrollBackward();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向右滑动元素
     *
     * @param b
     */
    public void swipForScrollableLeft(Object b) {
        if (b instanceof UiObject2) {
            ((UiObject2) b).scroll(Direction.LEFT, 0.8f);
        }
        if (b instanceof UiObject) {
            try {
                new UiScrollable(((UiObject) b).getSelector()).setAsHorizontalList().scrollBackward();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向上滑动元素
     *
     * @param b
     */
    public void swipForScrollableUp(Object b, float i) {
        if (b instanceof UiObject2) {
            ((UiObject2) b).scroll(Direction.UP, i);
        }
        if (b instanceof UiObject) {
            try {
                new UiScrollable(((UiObject) b).getSelector()).setAsVerticalList().scrollForward();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向上滑动元素
     *
     * @param b
     */
    public void swipForScrollableDown(Object b, float i) {
        Point p = getWindowSize();
        if (b instanceof UiObject2) {
            ((UiObject2) b).scroll(Direction.DOWN, i);
            device.swipe(p.x / 2, p.y / 2 + 500, p.x / 2, p.y / 2, 50);
        }
        if (b instanceof UiObject) {
            try {
                new UiScrollable(((UiObject) b).getSelector()).setAsVerticalList().scrollForward();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 点击元素
     *
     * @param b
     */
    public void click(Object b) {
        if (b instanceof UiObject2) {
            ((UiObject2) b).click();
        } else {
            try {
                ((UiObject) b).click();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 等待
     *
     * @param i
     */
    public void sleep(long i) {
        try {
            Thread.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 按返回键
     */
    public void back() {
        device.waitForIdle();
        device.pressBack();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void t() {
        Intent intent = new Intent();
        PackageManager pm = instrumentation.getContext().getPackageManager();
        Intent intent1 = pm.getLaunchIntentForPackage("com.Qunar");
//        for(String i :pm.getSystemSharedLibraryNames()){
//        Log.v("UIAUTOMATOR", "getScheme: " + i);}
//        Log.v("UIAUTOMATOR", "getScheme123: " + pm.resolveActivity();
        for (PackageInstaller.SessionInfo i : pm.getPackageInstaller().getAllSessions()) {
            Log.v("UIAUTOMATOR", "getScheme: " + i);
        }
    }

    /**
     * 返回元素的中心坐标
     *
     * @param b
     * @return
     */
    public Point getElementConcent(Object b) {
        Point p = new Point();
        if (b instanceof UiObject2) {
            Point p1 = ((UiObject2) b).getVisibleCenter();
            p.set(p1.x, p1.y);
        }
        if (b instanceof UiObject) {
            try {
                Rect r = ((UiObject) b).getVisibleBounds();
                p.set(r.centerX(), r.centerY());
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
        return p;
    }

    /**
     * 获得设备的窗口大小
     *
     * @return
     */
    public Point getWindowSize() {
        Point p = new Point();
        int x = device.getDisplayWidth();
        int y = device.getDisplayHeight();
        p.set(x, y);
        return p;
    }

    /**
     * 判断一个元素是否在底部
     *
     * @param b
     * @return
     */
    public boolean isBottom(Object b) {
        boolean t = false;
        Point pe = new Point(this.getElementConcent(b));
        Point pw = new Point(this.getWindowSize());
        if (pe.y > pw.y / 8 * 7) {
            t = true;
        }
        return t;
    }

    public void dumpPageFile(String name) {
        if (!name.toLowerCase().endsWith(".xml")) {
            name = name + ".xml";
        }
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + name);
        if (file.exists()) {
            file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        OutputStream out = null;
        try {
            out = new FileOutputStream(file, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            device.dumpWindowHierarchy(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void shotPhoto(String name) {
        String name1 = "";
        if (!name.toLowerCase().endsWith(".png")) {
            name1 = name.trim() + ".png";
        } else {
            name1 = name.trim();
        }
        File f = new File(Environment.getExternalStorageDirectory() + File.separator + "xz", name1);
        if (!f.getParentFile().exists()) {
            if (!f.getParentFile().mkdir()) {
                Log.i("UIAUTOMATOR", f.getParent() + "创建失败");
            }
        } else {
            if (f.getParentFile().isFile()) {
                f.getParentFile().delete();
                if (!f.getParentFile().mkdir()) {
                    Log.i("UIAUTOMATOR", f.getParent() + "创建失败");
                }
            }
        }
        if (f.exists()) {
            f.delete();
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        device.takeScreenshot(f);
    }

    public void assertFalse(boolean b, String name) {
        try {
            Assert.assertFalse(b);
        } catch (AssertionError e) {
            this.shotPhoto(name);
        }
    }

    public void waitForNewWindow(UiObject b) {
        try {
            b.clickAndWaitForNewWindow();
        } catch (UiObjectNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 把露出来的模块顶部滑动到屏幕中间
     *
     * @param u2
     */
    public void swipContent(UiObject2 u2) {
        int y = device.getDisplayHeight();
        int x = device.getDisplayWidth();
        int u2_y = u2.getVisibleBounds().top;
        if (u2_y > y / 5) {
            device.swipe(x / 2, u2_y, x / 2, y / 5, 50);
        }
        if (u2_y + 300 < y / 2) {
            u2_y = u2.getVisibleBounds().bottom;
            device.swipe(x / 2, u2_y + 300, x / 2, y / 2, 50);
        }
    }

    /**
     * 滑动到某一元素
     * @param by
     * @param f
     */
    public void swipToElement(BySelector by, float f) {
//        UiObject2 u2 = device.wait(Until.findObject(by), 20000);
        UiObject2 u2 = device.findObject(by);
        while (u2 == null) {
            swipForScrollableDown(UIHelper.getHomeElements().getHomeSwipElement(), f);
            u2 = device.findObject(by);
            UiObject2 u = device.findObject(By.text("周边游"));
            if (u != null) {
                Point p = getWindowSize();
                while (true) {
                    device.swipe(p.x / 2, p.y / 2 - 500, p.x / 2, p.y / 2, 50);
                    UiObject2 u1 = device.findObject(By.res("com.mqunar.atom.alexhome:id/atom_alexhome_mod_hotel"));
                    if (u1 != null) {
                        swipContent(u1);
                        break;
                    }
                }
                zuiJinGuanZhuHotel();
            }
        }
    }

    /**
     * 获取元素的大小
     * 目前没有测试准确
     * @param u2
     * @return
     */
    public Point getEleSize(UiObject2 u2) {
        Rect rect = u2.getVisibleBounds();
        int top = rect.top;
        int bottom = rect.bottom;
        int left = rect.left;
        int right = rect.right;
        Point point = new Point(right - left, bottom - top);
        return point;
    }

    /**
     * 点击元素
     * @param u
     */
    public void click(UiObject2 u) {
        device.waitForIdle(3000);
        Point p = u.getVisibleCenter();
        sleep(1000);
        device.click(p.x, p.y);
    }

    /**
     * 把字符串转换成小数
     * @param ss
     * @return
     */
    public float stringToFloat(String ss) {
        float f = 0.0f;
        String s = "[(0-9\\.)]{1,10}";
        Pattern pattren = Pattern.compile(s);
        Matcher m = pattren.matcher(ss);
        if (m.find()) {
            f = Float.parseFloat(m.group());
        }
        return f;
    }
}
